#-------------------------------------------------------------------------------
# Name:        Options
# Purpose:
#
# Author:      Pablo
#
# Created:     13/06/2012
# Copyright:   (c) Monxcleyr Productions 2012
# Licence:     GPL v3
#-------------------------------------------------------------------------------
#!/usr/bin/env python

import pygame, os, config
from ..gui import volumeslider, resslider

class Options():

  """Options menu """

  def __init__(self, surface, configfile, common, sound, music, debug, size):
    self.surface = surface
    self.configfile = configfile
    self.common = common
    self.settings = self.common.settings
    self.sound = sound
    self.music = music
    self.debug = debug
    self.size = size
    self.tempsize = size
    self.load()
    self.mouse = [(0,0), 0, 0, 0, 0, 0, 0]

    conf = config.Config()
    conf.read(os.path.join("resources/configs/" + self.configfile))

    self.musicloop = conf.get('Sounds', 'music')
    if self.musicloop == 'None':
      self.musicloop = None

    # Custom cursor
    self.mousevisable = conf.getboolean('Graphics', 'mousevisable')
    self.cursor = conf.get('Graphics', 'mousecustom')
    if self.cursor == 'None': self.cursor = None # Reset string to keyword
    if self.cursor != None:
      self.cursor = pygame.image.load(os.path.join('resources/graphics/' + self.cursor))
      self.cursor.set_colorkey((255,0,255))

    self.firstdraw = True # Just a variable for checking first time through draw loop

    # Background image loading
    self.bg = conf.getint_tuple('Graphics', 'bgcolor')
    bgimage = conf.get('Graphics', 'bgimage')
    if bgimage == 'None': bgimage = None #just making the string 'None' into the keyword None
    if bgimage != None:
      self.bgimage = pygame.image.load(os.path.join('resources/graphics/' + bgimage)).convert_alpha()
    else:
      self.bgimage = bgimage


    # Title image loading
    logoimage = conf.get('Graphics', 'logo')
    self.logopos = conf.getint_tuple('Graphics', 'logopos')# load uncentered position
    if logoimage == 'None': logoimage = None #just making the string 'None' into the keyword None
    if logoimage != None:
      self.logoimage = pygame.image.load(os.path.join('resources/graphics/' + logoimage)).convert_alpha()
      # center image:
      self.logopos = (self.logopos[0] - (self.logoimage.get_width() / 2), self.logopos[1] - (self.logoimage.get_height() / 2))
    else:
      self.logoimage = logoimage

    font = conf.get('Graphics', 'font')
    if font == 'None': font = None
    self.fontsize = conf.getint('Graphics', 'fontsize')
    self.font = pygame.font.Font(font, self.fontsize)

    self.volumetitle = conf.get('Volumeslider', 'title')
    self.soundtitle = conf.get('Soundslider', 'title')
    self.volumesound = conf.get('Volumeslider', 'sound')
    self.soundsound = conf.get('Soundslider', 'sound')
    self.volumepos = conf.getint_tuple('Volumeslider', 'position')
    self.soundpos = conf.getint_tuple('Soundslider', 'position')
    self.restitle = conf.get('ResolutionSlider', 'title')
    self.ressound = conf.get('ResolutionSlider', 'sound')
    self.respos = conf.getint_tuple('ResolutionSlider', 'position')

    self.volumeslider = volumeslider.VolumeSlider(self.volumepos, self.music_volume, self.music_setting, \
      self.surface, self.sound, self.volumesound, self.common, self.debug, self.volumetitle, self.font)
    self.soundslider = volumeslider.VolumeSlider(self.soundpos, self.sound_volume, self.sound_setting, \
      self.surface, self.sound, self.soundsound, self.common, self.debug, self.soundtitle, self.font)
    self.resslider = resslider.ResSlider(self.respos, self.tempsize, self.common.settings.fullscreen, \
      self.surface, self.sound, self.ressound, self.common, self.debug, self.restitle, self.font)

    # Find number of menu options
    checking = 1
    count = 1
    while checking == 1:
      if conf.has_section("Option" + str(count)) == True:
        count += 1
      else:
        checking = 0

    self.menu_item = []
    # Load up the menu options
    for i in range(1, count):
      pos = conf.getint_tuple("Option" + str(i),"position")
      button = conf.get("Option" + str(i),"button")
      buttonhover = conf.get("Option" + str(i),"buttonhover")
      clicksound = conf.get("Option" + str(i), "sound")
      mode = conf.get("Option" + str(i), "mode")
      if clicksound == 'None':
        clicksound = None
      self.menu_item.append(MenuItem(i, pos, button, buttonhover, clicksound, mode))


#-------------------------------------------------------------------------------
#-------------------------------------------------------------------------------


  def draw(self, mouse, prevmode):

    self.mouse = mouse
    self.debug.setRight("./resources/configs/" + self.configfile)

    if self.firstdraw == True:
      pygame.mouse.set_visible(self.mousevisable)
      if prevmode == 0:
        if self.music.getCurrentLoop() != self.musicloop:
          self.music.loadQueue(self.musicloop)
          self.music.playQueue()
      self.firstdraw = False

    # This is boilerplate code for running the music queue.
    if self.musicloop:
      if pygame.mixer.music.get_busy() == 0:
        self.music.playQueue()

    self.surface.fill(self.bg)
    if self.bgimage != None:
      self.surface.blit(self.bgimage, (0,0))

    # Title image
    if self.logoimage != None:
      self.surface.blit(self.logoimage, self.logopos)


    # Volume Slider
    self.volumeslider.draw(self.mouse)

    # Sound Slider
    self.soundslider.draw(self.mouse)

    # Update Volume dynamically
    if self.volumeslider.getVolume()[1] == True:
      tempvol = (self.volumeslider.getVolume()[0] * 5) * .01
    else:
      tempvol = 0
    pygame.mixer.music.set_volume(tempvol)
    if self.soundslider.getVolume()[1] == True:
      tempsoundvol = (self.soundslider.getVolume()[0] * 5)
    else:
      tempsoundvol = 0
    self.common.settings.sound_volume = tempsoundvol

    self.resslider.draw(self.mouse)

    # Check buttons to draw, hovered or normal:
    hover = self.getHover() # find a seclected button, if any
    for mitem in self.menu_item: #Get each menu item from the list
      if hover == mitem.id:
        self.surface.blit(mitem.buttonhover, mitem.pos)
      else:
        self.surface.blit(mitem.button, mitem.pos)


    if self.cursor != None:
      self.surface.blit(self.cursor, self.mouse[0])

    return self.surface

  def getHover(self):

    """ Returns hovered option. 0 if none."""

    selected = 0

    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse[0]):
        selected = self.menu_item[i].id

    return selected


  def getSelected(self):

    """ Returns selected option. 0 if none."""

    selected = 0
    mode = 0

    if self.mouse[1] == 1:
      pressed = True
    else:
      pressed = False
    for i in range(0, len(self.menu_item)):
      if self.menu_item[i].rect.collidepoint(self.mouse[0]) and pressed == True:
        self.sound.play(self.menu_item[i].sound, self.settings)
        selected = self.menu_item[i].id
        mode = self.menu_item[i].mode

    return selected, mode

  def save(self):
    """ Internal method for saving settings set in options menu"""
    res = self.resslider.getRes()
    self.common.settings.res_setting = self.common.reswidths.index(res[0])
    self.common.settings.fullscreen = res[1]
    self.common.settings.music_volume = self.volumeslider.getVolume()[0] * 5
    self.common.settings.music = self.volumeslider.getVolume()[1]
    self.common.settings.sound_volume = self.soundslider.getVolume()[0] * 5
    self.common.settings.sounds = self.soundslider.getVolume()[1]
    self.common.settings.activate()
    self.common.settings.save()
    self.load()

  def quit(self):
    """ Internal method for returning settings to original values"""
    self.common.settings.load()
##    self.common.settings.res_setting = self.common.reswidths.index(self.size[0])
##    self.common.settings.fullscreen = self.fullscreen
##    self.common.music_volume = self.music_volume
##    self.common.music = self.music_setting
##    self.common.sound_volume = self.sound_volume2
##    self.common.sounds = self.sound_setting
    self.common.settings.activate()
    self.common.settings.save()
    if self.music_volume % 5 != 0:
      tempvolume = self.music_volume / 5 + 1
    else:
      tempvolume = self.music_volume / 5
    self.volumeslider.tempvolume = tempvolume
    self.volumeslider.enabled = self.music_setting
    if self.sound_volume % 5 != 0:
      tempvolume = self.sound_volume / 5 + 1
    else:
      tempvolume = self.sound_volume / 5
    self.soundslider.tempvolume = tempvolume
    self.soundslider.enabled = self.sound_setting
    self.resslider.current = self.size[0]
    self.resslider.fullscreen = self.fullscreen
    self.load()

  def load(self):
    """ Internal method for copying settings variables into the option menu """

    self.res_setting = self.common.settings.res_setting
    self.music_volume = self.common.settings.music_volume
    self.sound_volume = self.common.settings.sound_volume
    self.music_setting = self.common.settings.music
    self.sound_setting = self.common.settings.sounds
    self.fullscreen = self.common.settings.fullscreen

    self.sound_volume2 = self.common.settings.sound_volume * 1

class MenuItem:
  def __init__(self, id, pos, button, buttonhover, sound, mode):

    self.id = id
    self.pos = pos
    self.button = pygame.image.load(os.path.join('resources/graphics/' + button)).convert_alpha()
    self.buttonhover = pygame.image.load(os.path.join('resources/graphics/' + buttonhover)).convert_alpha()
    #center image:
    self.pos = (pos[0] - (self.button.get_width() / 2), pos[1] - (self.button.get_height() / 2))
    self.rect = self.get_rect()
    self.sound = sound
    self.mode = mode

  def get_rect(self):
    return pygame.Rect(self.pos, (self.button.get_width(), self.button.get_height()))
